<template>
	<view class="v-home-page" :style="{ '--bg-image': `url(${ materialBg})` }">
		<view :style="{ height: navTop + 'px' }"></view>

		<view id="barTitle" :style="{ opacity: opacityStyle, height: heightSystemss+Number(50) + 'px' }"
			v-show="!hiddenModel">
			<text>本地上传</text>
		</view>

		<view class="flex-start-center " style="color:#333333" @click="localFn()">

			<uni-icons style="margin-top: 7rpx;" color="#333333" type="left" size="20"></uni-icons>
			<text style="color: 333333;font-size: 33rpx;"> 本地上传</text>
		</view>


		<view class="flex width100 relative margin-top_50rpx">
			<!-- <image @click.stop="videoUpload()" mode="widthFix" class="upload-img-cls" :src="szrImgBj"
				style="height: 1116.28rpx;"></image> -->


			<view @click.stop="videoUpload()" class="upload-img-cls bordColor" style="height: 900rpx;">

			</view>




			<view class="upload-bj-cls flex-column">
				<block v-if="!videoShowUrl">
					<uni-icons type="plusempty" size="30"></uni-icons>
					<view>点击上传视频（必选）</view>
					<text>上传的视频必须带有口播语音</text>
				</block>
				<block v-else>
					<video :src="videoShowUrl.split('?')[0]"
						:poster="videoShowUrl.split('?')[0] + '?x-oss-process=video/snapshot,t_1000,f_jpg,m_fast'"
						style="width: 550rpx;height: calc(100% - 0rpx);position: relative;z-index: 999;">
					</video>
				</block>

				<!-- <uni-icons v-if="videoShowUrl" @click='closeVideo()' color="#ff0000" class="uniIcons" type="closeempty"
					size="22" style=" position: absolute; top: 28rpx;left:580rpx;z-index: 99999; right:586rpx;">
				</uni-icons> -->
				
				<image v-if="videoShowUrl"  :src="closeVideo" mode=""  @click='closeVideoFn()' style=" position: absolute; top: 28rpx;left:560rpx;z-index: 99999; right:586rpx;height: 50rpx;width: 50rpx;"></image>
			</view>
		</view>

		<view class="">
			<view class="v-title flex-align-center">
				<text></text>
				<view>视频要求</view>
			</view>

			<view v-if="faddish_notice" style="margin: 0 20rpx;" class="v-padding-center margin-top_16rpx">
				<uv-parse class="" :content="faddish_notice" :selectable="true"></uv-parse>
			</view>
		</view>
		<view class="height80">

		</view>


		<view class="c-but flex" @click="but()">开始训练 {{'('+"算力："+tallySet.extract_tally+')'}}</view>
		<sunui-popup ref="serviceItemsPopup">
			<template v-slot:content>

				<view class="serviceItemsContain ">
					<view class="top flex-between">
						<view class="">

						</view>
						<text>任务标题</text>
						<uni-icons @click='closeWriteOffIcon()' class="uniIcon" type="closeempty" size="22"
							style="color: #07070791;">
						</uni-icons>
					</view>

					<view class="card margin-bottom_50rpx">
						<view class="myNmae">

							<view class="">
								<input class="uni-inputsa" type="text" v-model="name" placeholder="请输入标题" />
							</view>


						</view>

					</view>

					<view class="PublishTags flex" @click="payNow()">
						一键分析
					</view>

				</view>

			</template>
		</sunui-popup>




	</view>
</template>

<script>
	const base64 = require('@/utils/ali-oos/base64.js'); //Base64,hmac,sha1,crypto相关算法
	require('@/utils/ali-oos/hmac.js');
	require('@/utils/ali-oos/sha1.js');
	const Crypto = require('@/utils/ali-oos/crypto.js');
	export default {
		data() {
			return {
				hiddenModel: true, //显示影藏
				opacityStyle: 0, //透明度
				heightSystemss: "",
				materialBg: this.$imgs.violet,
				closeVideo:this.$imgs.closeVideo,
				navTop: '',
				name: '',

				videoShowUrl: '',

				szrImgBj: 'https://yuntt.weijuyunke.com/yunttXcxImage/digitalPeople/szrImgBj.png',
				richText: '',

				tempFiles: [], //上传获取到的文件数组
				/* 上传视频start */
				formData: {
					key: '',
					policy: '',
					OSSAccessKeyId: '',
					signature: '',
					success_action_status: '200'
				},

				policyText: {
					expiration: '2050-01-01T12:00:00.000Z', //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
					conditions: [
						['content-length-range', 0, Number(uni.getStorageSync('upload_allow_size'))] // 设置上传文件的大小限制(104857600为：100MB，31457280为30MB)
					]
				},

				id: '',

				upPicUrl2: '',
				ossUrl: '', //上传阿里云返回视频路径
				/* 上传视频end */

				tallySet: uni.getStorageSync('tallySet'),
				user: uni.getStorageSync('user'),
				faddish_notice: '',
				duration: '',
				memberSetObj: {},
				tempFilesRes:''

			}
		},
		onLoad() {
			const app = getApp();
			this.navTop = app.globalData.navTop;

			this.set();
			this.createdgetSystemInfo();
			this.userInfos()
			this.tallySetFn()
			this.faddishNotice()
			this.memberSetFn()
			console.log(uni.getStorageSync('upload_allow_size')/ 1024 / 1024,'测试')

		},
		computed: {


		},
		onHide() {
			console.log('页面隐藏')
			clearInterval(this.timer);




		},
		onPageScroll(ev) {


			if (ev.scrollTop > 10) {
				let opacity = ev.scrollTop / 140

				// this.opacityStyle = opacity > 1 ? 1 : opacity
				this.opacityStyle = 1
				this.hiddenModel = false
				// this.createdgetSystemInfo();

			} else {
				this.hiddenModel = true
			}
		},
		// 监听页面卸载
		onUnload() {
			console.log('页面隐藏')
			clearInterval(this.timer);




		},
		methods: {
			async faddishNotice() {
				const result = await this.$http.get({
					url: this.$api.clipSet,

				});
				if (result.errno == 0) {
					console.log(result.data.faddish_notice)
					this.faddish_notice = result.data.faddish_notice


				}
			},
			async userInfos() {
				const result = await this.$http.get({
					url: this.$api.userInfo,
					data: {
						// 用户id
						uid: uni.getStorageSync('uid'),
						// 上级id
						// pid: ''
					}
				});
				if (result.errno == 0) {
					this.user = result.data;

					uni.setStorageSync('user', result.data);


				}
			},
			async tallySetFn() {
				const result = await this.$http.get({
					url: this.$api.tallySet,

				});
				if (result.errno == 0) {
					console.log(result.data)

					uni.setStorageSync('tallySet', result.data);



				} else {
					this.$sun.toast(result.message, 'none')
				}
			},
			createdgetSystemInfo() {
				let menuButtonObject = uni.getMenuButtonBoundingClientRect(); //获取菜单按钮（右上角胶囊按钮）的布局位置信息。坐标信息以屏幕左上角为原点。
				uni.getSystemInfo({
					//获取系统信息
					success: res => {
						let navHeight = menuButtonObject.height + (menuButtonObject.top - res
							.statusBarHeight) * 2; //导航栏高度=菜单按钮高度+（菜单按钮与顶部距离-状态栏高度）*2
						this.heightSystemss = navHeight;
						console.log(navHeight, '==========================')

					},
					fail(err) {
						console.log(err);
					}
				});
			},
			closeVideoFn() {
				this.videoShowUrl = ''
			},
			/*  阿里云设置  */
			async set() {
				const result = await this.$http.get({
					url: this.$api.uploadSet,

				});
				if (result.errno == 0) {
					// accessKey 阿里云key秘钥 accessId 阿里云id
					console.log('result', result);
					this.upPicUrl2 = 'https://' + result.data.alioss_domain;
					this.formData.OSSAccessKeyId = result.data.alioss_access_key_id;
					this.formData.policy = base64.encode(JSON.stringify(this.policyText));
					let message = this.formData.policy;
					let bytes = Crypto.HMAC(Crypto.SHA1, message, result.data.alioss_access_key_secret, {
						asBytes: true
					});
					this.formData.signature = Crypto.util.bytesToBase64(bytes);

					console.log('------------formData', this.formData);
				}
			},
			localFn() {
				this.$sun.navBack()
			},
			async payNow() {



				if (!this.name) {
					this.$sun.toast('请输入标题', 'none')
					return
				}

				if (!this.videoShowUrl) {
					this.$sun.toast('请上传视频后在提交', 'none')
					return
				}






				uni.showLoading({
					title: '视频正在分析中请稍等...',
					mask: true
				});
				this.$refs.serviceItemsPopup.close()
				const result = await this.$http.post({
					url: this.$api.faddishSave,
					data: {
						uid: uni.getStorageSync('uid'),
						name: this.name,
						type: 1,
						url: this.videoShowUrl,
						from: 0



					}
				});
				if (result.errno == 0) {

					uni.hideLoading()
					console.log(result.data)

					// this.id = result.data.id

					
					// this.$sun.navGo('/pagesA/creatCenter/piecemeal/uploadStepsOne?obj=' + encodeURIComponent(JSON
					// 	.stringify({
					// 		content: [result.data.content],
					// 		id: this.id
					// 	})))
					
					this.$sun.navTo('/pagesA/creatCenter/HotSelling/HotSellingList')



				} else {
					uni.hideLoading()
					setTimeout(() => {
						this.$sun.toast(result.message, 'none')
					}, 200)
				}




			},

			closeWriteOffIcon() {

				uni.hideLoading()
				clearInterval(this.timer);
				this.$refs.serviceItemsPopup.close()
			},
			async faddishResult() {
				clearInterval(this.timer);
				const result = await this.$http.post({
					url: this.$api.faddishResult,
					data: {
						uid: uni.getStorageSync('uid'),
						task_id: this.id,

					}
				});
				if (result.errno == 0) {
					// accompaniment: "https://yunhunjian123.oss-cn-shanghai.aliyuncs.com/Q5gU-1750754755_accompaniment.wav"
					// content: "九十九元五斤的小龙虾个头也是不小的有喜欢吃小龙虾的可以过来尝试一下"
					// vocals: "https://yunhunjian123.oss-cn-shanghai.aliyuncs.com/Q5gU-1750754755_vocals.wav"
					this.$refs.serviceItemsPopup.close()
					console.log(result.data)
					this.$sun.navGo('/pagesA/creatCenter/piecemeal/uploadStepsOne?obj=' + encodeURIComponent(JSON
						.stringify({
							...result.data,
							id: this.id
						})))

					clearInterval(this.timer);

				} else if (result.errno == -1) {

					clearInterval(this.timer);
					this.$sun.toast(result.message, 'none')

					// if(result.message=='分析中，请等待刷新'){
					// 	this.timer = setInterval(() => {
					// 		this.faddishResult();
					// 	}, 3000);
					// }
				} else {
					this.$sun.toast(result.message, 'none')

					this.timer = setInterval(() => {
						this.faddishResult();
					}, 4000);
				}
			},

			async memberSetFn() {
				const result = await this.$http.get({
					url: this.$api.memberSet,
					data: {


					}
				});
				if (result.errno == 0) {

					this.memberSetObj = result.data

					console.log(result.data)

				}
			},

			but() {

				if (this.user.is_member == 0 && this.memberSetObj.is_open == 1) {
					uni.showModal({
						title: '温馨提示',
						content: '你当前不是会员，请开通会员后享受该功能',
						confirmText: '开通会员',
						confirmColor: '#4A5EFF',
						success: async (res) => {
							if (res.confirm) {


								this.$sun.navGo('/pages/contactUs/memberCenter')

							} else if (res.cancel) {

							}
						}
					});
				} else {
					this.$refs.serviceItemsPopup.show({
						anim: 'bottom',
						position: 'bottom',
						shadeClose: false, //false使用户不能点击其它关闭页面
						topclose: false,
						zIndex: 99999
					});
				}

			},

			// “上传文件” 视频点击事件
			videoUpload() {
				let that = this;
				uni.chooseVideo({
					sourceType: ['album'],
					compressed:false,
					// 如果type属性和extension同时存在，例如{type:'image',extension:['.png','.jpg']}，则会选择image/png,image/jpg文件
					// 如果只配置extension属性，例如{extension:['.doc','.xlsx','.docx']}，则会选择.doc,.xlsx,.docx文件，详情见accept属性
					// 在微信环境中，如果type="all"，则extension属性失效
					count: 1, //选取的文件个数限制
					// type: 'video', //all	从所有文件选择    video	只能选择视频文件   image	只能选择图片文件
					extension: ['.mp4', '.3gp', '.mov'], //可定义允许哪些后缀的文件可被选择
					success: res => {
						// let allLength = that.tempFiles.length + res.tempFilePath.length;
						console.log('点击上传事件res.tempFiles', res.tempFilePath.length, 'that.tempFiles', that
							.tempFiles.length);
						// if (allLength > 1) {
						// 	this.$sun.toast('当前限制选择 1 个文件');
						// 	return;
						// }
						that.tempFiles = [res.tempFilePath]; //要上传的文件
						
						that.tempFilesRes = [res];
						console.log('tempFiles======', that.tempFiles, 'res', res);
						this.duration = res.duration
						this.startUploading();
					}
				});
			},

			// 开始上传
			async startUploading() {
				// let that = this;
				// this.numCount = 0;
				if (this.tempFiles.length <= 0) {
					this.$sun.toast('请先上传文件', 'none');
					return;
				}

				let isLt = true;
				let numSize = Number(uni.getStorageSync('upload_allow_size'))/ 1024 / 1024;
				for (let i = 0; i < this.tempFiles.length; i++) {
					// 判断是否小于2mb
					if (this.tempFilesRes[i].size / 1024 / 1024 > numSize) {
						isLt = false;
					}
				}
				if (!isLt) {
					for (let i = 0; i < this.tempFiles.length; i++) {
						// 判断是否小于2mb
						if (this.tempFilesRes[i].size / 1024 / 1024 > numSize) {
							console.log('进入删除', i);
							this.tempFiles.splice(i, 1);
						}
					}
					this.$sun.toast('请上传小于' +  numSize.toFixed(2) + 'MB文件', 'none');
					return;
				}

				uni.showLoading({
					title: '上传中...'
				});
				for (let i = 0; i < this.tempFiles.length; i++) {
					let markIndex = this.tempFiles[i].lastIndexOf('.');
					let suffix = this.tempFiles[i].substring(markIndex);
					this.formData.key = new Date().getTime() + Math.floor(Math.random() * 150) + suffix;

					console.log('this.formData.key', this.formData.key, 'this.tempFiles[i].name', this.tempFiles[i]
						.name, 'this.tempFiles[i]', this.tempFiles[i]);

					// fileUrl放在上传（uploadFile）内，则只能获取到最后一个值
					let fileUrl = this.upPicUrl2 + '/' + this.formData.key;
					let formData = {
						...this.formData
					}; //需要这样赋值，否则for循环传值一致 
					// let type = this.tempFiles[i].type; //需要这样赋值，否则for循环传值一致
					console.log('fileUrl, type123', fileUrl, suffix, 'this.formData', this.formData);
					uni.uploadFile({
						name: 'file', //文件上传的name值
						url: this.upPicUrl2, //接口地址
						formData: formData, //上传额外携带的参数
						filePath: this.tempFiles[i], //临时路径
						success: uploadFileRes => {
							console.log('this.formData222222', this.formData);
							if (uploadFileRes.statusCode != 200) {
								uni.showToast({
									title: '上传失败 : ' + uploadFileRes.data,
									icon: 'none'
								});
							} else {
								console.log('this.tempFiles[i]', this.tempFiles[i], 'uploadFileRes',
									uploadFileRes)
								uni.hideLoading();
								this.videoShowUrl = fileUrl;
								// 注册媒资 
								// this.registerMedias(fileUrl, suffix);
							}
						},
						fail: e => {
							uni.hideLoading();
							console.log(e)
							uni.showToast({
								title: '上传失败==>' + e,
								icon: 'none'
							});
						}
					});
				}
			},


			// 注册媒资
			async registerMedias(url, type) {
				const result = await this.$http.post({
					url: this.$api.registerMediaMp4,
					data: {
						mediaUrl: url, //上传阿里云生成的地址
						mediaType: type, //文件类型
						username: uni.getStorageSync('merchantCode')
					}
				});
				if (result.code == 2000) {
					console.log('注册媒资result', result.data);
					this.videoDuration = result.data.duration; //“上传视频”时长

					this.$sun.toast('上传成功');
					this.tempFiles = [];
					uni.hideLoading(); //清除加载中
				} else {
					uni.hideLoading();
				}
			},


		}
	}
</script>

<style lang="less">
	.v-home-page {
		background-image: (var(--bg-image));
		background-repeat: no-repeat;
		background-size: contain;
		position: relative;
		height: 100vh;
		padding: 20rpx;
		background-color: #fff !important;

		#barTitle {
			position: fixed;
			width: 750rpx;
			top: 0;
			left: 0;
			background: #fff;
			color: #000000;
			text-align: center;
			font-weight: bold;
			z-index: 999999
		}

		#barTitle>text {
			position: absolute;
			left: 0;
			right: 0;
			bottom: 20rpx
		}




		.serviceItemsContain {
			padding: 0rpx 30rpx 30rpx 30rpx;
			background-color: #fff;

			height: auto;
			overflow-x: auto;

			.PublishTags {
				z-index: 99;
				margin-top: 10rpx;
				height: 102rpx;
				border-radius: 20rpx;
				color: #fff;


				bottom: 20rpx;
				background: rgb(120, 93, 246);
			}

			.myNmae {

				background-color: #fff;
				min-width: 50rpx;

				.avatar {
					width: 84rpx;
					height: 84rpx;
				}

				input {
					text-align: left;
				}

				.uni-input {

					height: 100rpx;
				}

				.uni-inputsa {
					width: 100%;
					height: 90rpx;
					border-radius: 20rpx;
					background: rgb(245, 245, 245);
					margin: 20rpx 0;
					padding: 0rpx 20rpx;
				}

				.uni-inputs {
					text-align: left !important;
				}

				.backgroundImg {

					height: 154rpx;


				}

			}





			.top {
				padding: 30rpx 0;
				width: 100%;

				text {
					color: rgb(0, 0, 0);
					font-size: 36rpx;
					font-weight: 400;
				}
			}

		}


		.upload-bj-cls {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			margin: auto;

			::v-deep .uni-icons {
				position: relative;
				right: 0;
				z-index: 9999
			}

			image {
				width: 84rpx;
			}

			view {
				color: rgb(141, 84, 242);
				font-size: 32rpx;
				font-weight: 600;
				margin: 26rpx 0 14rpx;
			}

			text {
				color: rgb(153, 153, 153);
				font-size: 24rpx;
				font-weight: 400;
			}
		}

		.upload-img-cls {
			width: 500rpx;
			position: relative;


			z-index: 99;
		}

		.bordColor {
			border: 4rpx solid transparent;
			/* 必须设置 border 属性 */
			// width: 400rpx;
			// height: 400rpx;
			border-image: linear-gradient(45deg, rgba(255, 218, 148, 1), rgba(179, 130, 255, 1)) 1;
			border-radius: 20rpx;
			/* 设置圆角 */

		}

		.v-title {
			margin-top: 60rpx;
			// padding: 0rpx 26rpx 42rpx;

			text {
				width: 10rpx;
				height: 24rpx;
				border-radius: 138rpx;

				background: #7266FF;
			}

			view {
				margin-left: 10rpx;
				font-size: 34rpx;
				font-weight: bold;
			}
		}

		// 按钮样式
		.c-but {

			font-weight: 700;

			padding: 20rpx 40rpx;

			// color: #ffffff;
			width: 90%;
			position: fixed;
			bottom: 40rpx;
			left: 3%;
			border: none;

			z-index: 999;


			border-radius: 20rpx;
			margin: 20rpx;
			text-align: center;
			font-size: 32rpx;
			height: 100rpx;
			margin-top: 30rpx;
			color: #ffffff;
			background: linear-gradient(90deg, #6475FF, #7464FF 100%);
		}

		page {
			background-color: #fff !important;
		}

		;
	}
</style>